import React from 'react';
import classNames from 'classnames';
import ConfigProvider from '../config-provider';

interface IconProps {
  type?: string; // icon 名称
  className?: string; // 样式名
  style?: React.CSSProperties; // 内联样式
  component?: React.ComponentType<React.SVGProps<SVGSVGElement>>; // 自定义Icon，根标签为 <svg> 的 React 组件
  spin?: boolean; // 是否有旋转动画
  onClick?: (event: React.MouseEvent<HTMLSpanElement>) => void;
  loading?: boolean; // 按钮是否loading
  disabled?: boolean; // 是否禁用
  size?: string;
}

const InternalIcon = (props: IconProps, ref: React.Ref<HTMLSpanElement>) => {
  const { iconPrefixCls, size: contextSize } = React.useContext(ConfigProvider.ConfigContext);
  const { type = '', className, component: Component, spin, onClick, loading, disabled, size = contextSize, ...rest } = props;

  // ref
  const innerRef = React.useRef<HTMLElement>();
  const iconRef = (ref as any) || innerRef;

  // icon组件前缀

  // icon  class
  const iconClasses = classNames(iconPrefixCls, className, {
    [`${type}`]: true,
    [`${iconPrefixCls}-size-${size}`]: size, // 尺寸样式
    [`${iconPrefixCls}-spin`]: !!spin || !!loading, // 旋转
    'is-click': onClick, // 点击事件时 icon的hover样式
    'is-disabled': !!disabled
  });

  // icon 点击事件
  const handleClick = (e: React.MouseEvent<HTMLSpanElement>) => {
    onClick?.(e);
  };

  // 节点渲染
  const renderInnerNode = () => {
    if (Component) {
      return <Component />;
    }

    return null;
  };

  return (
    <span role="img" className={iconClasses} {...rest} ref={iconRef} onClick={handleClick}>
      {renderInnerNode()}
    </span>
  );
};

const Icon = React.forwardRef<HTMLSpanElement, IconProps>(InternalIcon);

export default Icon;
